import database, services
from database import Currency, Account, User
import AuthenticationService
from sqlalchemy.sql.expression import BooleanClauseList, operators

def saveOrUpdateAccount(login, account):
    session = database.getSession()

    existingAccount = getAccounts(login, id=account.id)
    with session.begin():
        if (existingAccount == None):
            user = AuthenticationService.getUser(login)
            account.user = user
            session.add(account)
        else:
            existing = existingAccount[0]
            del existing.initialAmounts
            existing.name = account.name
            existing.initialAmounts = account.initialAmounts
    return account.id

def getAccounts(login, id=None, accountName=None):
    """Provides accounts if exists, otherwise None.

    :param login: owner's login of this account
    :param id: optional, id of account
    :param accountName: optional, name of account
    """
    session = database.getSession()

    with session.begin():
        accountFilter = BooleanClauseList(operator=operators.and_, *(User.login == login, ))
        if (id != None): accountFilter.append(Account.id == id)
        if (accountName != None): accountFilter.append(Account.name == accountName)
        accounts = session.query(Account) \
                            .join(Account.user) \
                            .filter(accountFilter) \
                            .all()
        return [accounts, None][len(accounts) == 0]

def getCurrency(currency):
    session = database.getSession()

    with session.begin():
        return session.query(Currency).filter(Currency.code == currency).one()
